package com.xyd.util;

import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 类描述：mybatis工具类
 *
 * @author 张吉哲
 * @date 2021/1/6 13:44
 */
public class MybatisUtil {

  private static SqlSessionFactory sqlSessionFactory;

  static {
    try {
      Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 创建SqlSession，默认开启事务，需要手动提交
   *
   * @return SqlSession
   */
  public static SqlSession getSqlSession() {
    return sqlSessionFactory.openSession();
  }

  /**
   * 重载创建SqlSession方法，设置是否自动提交
   *
   * @param autoCommit true:自动提交；false:开启事务，手动提交
   * @return SqlSession
   */
  public static SqlSession getSqlSession(boolean autoCommit) {
    return sqlSessionFactory.openSession(autoCommit);
  }

  /**
   * 关闭SqlSession对象
   *
   * @param sqlSession 被关闭的SqlSession
   */
  public static void closeSqlSession(SqlSession sqlSession) {
    sqlSession.close();
  }
}
